<?php
/**
 * Created by PhpStorm.
 * User: ycbwl
 * Date: 2018/10/27
 * Time: 3:01 PM
 */
namespace app\api\service;
use app\api\model\Order as OrderModel;
use app\api\model\Product;
use app\api\Service\Order as OrderService;
use app\lib\enum\OrderStatusEnum;
use think\Db;
use think\Exception;
use think\facade\Log;


include APP_PATH."extend/WxPay/WxPay.Api.php";
class WxNotify extends \WxPayNotify{


    public function NotifyProcess($data, &$msg)
    {
        if($data['result_code'] == 'SUCCESS'){
            $orderNo = $data['out_trade_no'];
            Db::startTrans();
            try{
                $order = OrderModel::where("order_no",$orderNo)->lock(true)->find();
                if($order->status == 1){
                    $service = new OrderService();
                    $stockStatus = $service->checkOrderStock($order->id);
                    if($stockStatus['pass']){
                        $this->updateOrderStatus($order->id,true);
                        $this->reduceStock($stockStatus);
                    }else{
                        $this->updateOrderStatus($order->id,false);
                    }
                }
                Db::commit();
                return true;
            }catch (Exception $exception){
                Db::rollback();
                Log::record('微信支付回调失败','wxCallback-error');
                return false;
            }
        }
    }


    private function reduceStock($stockStatus){
        foreach($stockStatus['pStatusArray'] as $k=>$v){
            Product::where("id",$v['id'])->setDec('stock',$v['count']);
        }
    }

    private function updateOrderStatus($orderID,$success){
        $status = $success?OrderStatusEnum::PAID:OrderStatusEnum::PAID_BUT_OUT_OF;
        OrderModel::where("id",$orderID)->update(['status'=>$status]);
        return true;
    }





}